<template>
  <div class="w640 bgfff dg-add">
    <yd-cell-item arrow type="label">
      <span slot="left">选择类别：</span>
      <select slot="right" v-model="dg_type" @change="selectType(dg_type)">
        <option value="">请选择类别</option>
        <option value="景点">景点</option>
        <option value="美食">美食</option>
        <option value="资讯">资讯</option>
      </select>
    </yd-cell-item>
    <yd-cell-item>
      <span slot="left">{{dg_type}}名称：</span>
      <yd-input slot="right" required v-model="dg_title" max="30" placeholder="请输入名称"></yd-input>
    </yd-cell-item>
    <yd-cell-item>
        <span slot="left">上传{{dg_type}}封面：</span>
        <div slot="right">
          <yd-button type="primary" slot="right">选择图片</yd-button>
          <form id="uploadCover">
            <input type="file" slot="right" id="chooseCover" accept="image" @change="uploadCover"/>
          </form>
        </div>
    </yd-cell-item>

    <yd-cell-item v-if="dg_cover.length>0">
      <img class="cover-img" slot="right" v-if="dg_cover" :src="dg_cover"/>
    </yd-cell-item>

    <yd-cell-group :title="dg_type+'描述'" style="margin-bottom: 0">
        <!--<textarea   maxlength="500" v-model="dg_desc"></textarea>-->
      <div id="editor" type="text/plain" style="height:3rem;"></div>
    </yd-cell-group>



    <yd-cell-item type="label">
      <div slot="left">{{dg_type}}是否推荐</div>
      <yd-switch slot="right" v-model="dg_recom"></yd-switch>
    </yd-cell-item>


   <div style="padding:0.3rem;padding-top: 0;padding-bottom: 1rem">
     <yd-button v-if="!isEdit" size="large" type="primary" shape="circle" @click.native="startSave">提交保存</yd-button>
     <yd-button v-if="isEdit"  size="large" type="danger" shape="circle" @click.native="startUpdate">保存更改</yd-button>
     <div style="text-align: center;font-size: 0.36rem;color: #ff4300;margin-top: 0.3rem"><a href="#/dgList" >查看列表</a></div>
   </div>

    <!-- 遮罩层 -->
    <div id="demo" class="cropperImg">
      <div class="container" v-show="uploadMask">
        <div>
          <img id="image" :src="url" alt="Picture">
        </div>
        <button type="button" id="button" @click="crop">确定</button>
        <button type="button" id="cancel_crop" @click="uploadMask=false">取消</button>
      </div>
    </div>

  </div>
</template>

<script>
  import Vue from 'vue';
  import { Toast,Loading } from 'vue-ydui/dist/lib.rem/dialog';
  import {CellGroup, CellItem} from 'vue-ydui/dist/lib.rem/cell';
  import {TextArea} from 'vue-ydui/dist/lib.rem/textarea';
  import {Switch} from 'vue-ydui/dist/lib.rem/switch';
  import {Button} from 'vue-ydui/dist/lib.rem/button';
  import {Input} from 'vue-ydui/dist/lib.rem/input';

  import Cropper from 'cropperjs'
  import '../assets/css/cropper.css'

  Vue.component(Button.name, Button);
  Vue.component(Input.name, Input);
  Vue.component(Switch.name, Switch);
  Vue.component(TextArea.name, TextArea);
  Vue.component(CellGroup.name, CellGroup);
  Vue.component(CellItem.name, CellItem);
    export default {
      data() {
        return {
          dg_title: '',
          dg_cover: '',
          dg_desc: '',
          dg_recom: false,
          isEdit: false,
          did: '',
          dg_type:'景点',
          ue:null,
          picValue: '',
          cropper: '',
          croppable: false,
          uploadMask: false,
          url: '',
          avaPath:'',
          isUpload:false
        }
      },
      destroyed(){
        this.ue.destroy();
      },
      created() {
        var ls = localStorage.getItem("dgUser");
        if (!ls || ls !== 'qun') {
          this.$router.replace('/dgLogin');
        }
      },

      mounted() {

        document.title = "添加地点";
        this.did = this.$route.params.did;
        if (this.did) {
          this.isEdit = true;
          this.$nextTick(function () {
            this.getInfo();
          })
        }
        this.ue = UE.getEditor('editor',{
          BaseUrl: '',
          UEDITOR_HOME_URL: '/static/ueditor/',
        });
        //初始化这个裁剪框
        var self = this;
        var image = document.getElementById('image');
        this.cropper = new Cropper(image, {
          aspectRatio: 16/9,
          viewMode: 1,
          background: false,
          zoomable: true,
          ready: function () {
            self.croppable = true;
          }
        });
      },
      methods: {

        add(url) {
          if (!this.dg_title) {
            Toast({mes: "标题必填", time: 1000});
            return false;
          }
          if (this.dg_recom && !this.dg_cover) {
            Toast({mes: "推荐内容封面必填", time: 1000});
            return false;
          }
          this.dg_desc=UE.getEditor('editor').getContent();
          this.$axios.post(url, {
            'did': this.did,
            'dg_title': this.dg_title,
            "dg_cover": this.dg_cover,
            "dg_desc": this.dg_desc,
            "dg_recom": this.dg_recom,
            "dg_type":this.dg_type
          }).then((res) => {
            let jsons = res.data;
            if(jsons.success){
              Toast({
                mes: jsons.msg, time: 1000, callback: () => {
                  this.$router.replace("/dgSuccess");
                }
              });
            }
            else{
              Toast({
                mes: '修改失败'
              });
            }

          })
        },
        startSave() {
          this.add("/donggu/save")
        },

        startUpdate() {
          this.add("/donggu/update")
        },
        getInfo() {
          this.$axios.post("/donggu/info", {
            did: this.$route.params.did
          }).then((res) => {
            let resData = res.data;
            if (resData.success) {
              let r = resData.result;
              this.dg_title = r.dg_title;
                this.dg_cover = r.dg_cover;
                this.dg_recom = r.dg_recom;
                this.dg_desc=r.dg_desc;
                this.dg_type=r.dg_type;
              this.ue.addListener("ready",()=>{
                this.ue.setContent(r.dg_desc); // 确保UE加载完成后，放入内容。
              });
            }

          });

        },
        selectType(v){
          this.dg_type=v;
          this.dg_type=this.dg_type
        },
        getObjectURL(file) {
          var url = null;
          if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
          } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
          } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
          }
          return url;
        },
        uploadCover(e) {
          let files = e.target.files || e.dataTransfer.files;
          if (!files.length) return;
          this.uploadMask = true;
          this.picValue = files[0];

          this.url = this.getObjectURL(this.picValue);
          //每次替换图片要重新得到新的url
          if (this.cropper) {
            this.cropper.replace(this.url);
          }
          this.uploadMask = true;

        },
        crop() {
          this.uploadMask = false;
          var croppedCanvas;
          var roundedCanvas;

          if (!this.croppable) {
            return;
          }
          // Crop
          croppedCanvas = this.cropper.getCroppedCanvas();
          roundedCanvas = this.getRoundedCanvas(croppedCanvas);
          this.headerImage = roundedCanvas.toDataURL('image/jpeg', 0.9);//图片压缩0.9
          this.postImg()
        },
        getRoundedCanvas(sourceCanvas) {

          var canvas = document.createElement('canvas');
          var context = canvas.getContext('2d');
          var width = sourceCanvas.width;
          var height = sourceCanvas.height;

          canvas.width = width;
          canvas.height = height;

          context.imageSmoothingEnabled = true;
          context.drawImage(sourceCanvas, 0, 0, width, height);

          context.globalCompositeOperation = 'destination-in';
          context.beginPath();
          context.fillRect(0, 0,width, height);
          return canvas;
        },
        //提交图片给后台
        postImg() {
          this.$axios.post("/donggu/uploadCover", {
            base64Data: this.headerImage,
          }).then((res) => {
            let jsons = res.data;
            if (jsons.success) {
              document.getElementById("chooseCover").value="";
              this.dg_cover=jsons.result.dg_cover;
              this.isUpload=true;
            }

            Toast({mes: res.data.msg})
          })
        }
      }
    }
</script>
